package org.github.core.satoken;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.SaTokenException;
import cn.hutool.core.lang.Pair;
import java.util.Objects;
import lombok.extern.slf4j.Slf4j;
import org.github.core.spring.restful.Base;
import static cn.dev33.satoken.exception.NotLoginException.BE_REPLACED;
import static cn.dev33.satoken.exception.NotLoginException.INVALID_TOKEN;
import static cn.dev33.satoken.exception.NotLoginException.KICK_OUT;
import static cn.dev33.satoken.exception.NotLoginException.NOT_TOKEN;
import static cn.dev33.satoken.exception.NotLoginException.TOKEN_TIMEOUT;
import static org.github.core.spring.util.MessageSourceUtil.i18n;
import static org.springframework.http.HttpStatus.BAD_REQUEST;

@Slf4j
public abstract class SaTokenExceptionConverter {
  public static Pair<Base,Boolean> convert(SaTokenException e) {
    if (e instanceof NotLoginException) {
      return Pair.of(handleNotLoginException(((NotLoginException) e)), false);
    }
    if (e.getCause() != null && e.getCause() instanceof NotLoginException) {
      return Pair.of(handleNotLoginException(((NotLoginException) e.getCause())), false);
    }
    //TODO
    log.warn("未经转化的sa-token异常", e);
    return Pair.of(Base.of(BAD_REQUEST, null), false);
  }

  public static Base handleNotLoginException(NotLoginException e) {
    if (Objects.equals(e.getType(), NOT_TOKEN)) {
      String msg = i18n("sa.not.token");
      return Base.of(BAD_REQUEST, msg);
    } else if (Objects.equals(e.getType(), INVALID_TOKEN)) {
      String msg = i18n("sa.invalid.token");
      return Base.of(BAD_REQUEST, msg);
    } else if (Objects.equals(e.getType(), TOKEN_TIMEOUT)) {
      String msg = i18n("sa.token.timeout");
      return Base.of(BAD_REQUEST, msg);
    } else if (Objects.equals(e.getType(), BE_REPLACED)) {
      String msg = i18n("sa.be.replaced");
      return Base.of(BAD_REQUEST, msg);
    } else if (Objects.equals(e.getType(), KICK_OUT)) {
      String msg = i18n("sa.kick.out");
      return Base.of(BAD_REQUEST, msg);
    } else {
      String msg = i18n("sa.not.login");
      return Base.of(BAD_REQUEST, msg);
    }
  }
}
